package com.xiaoma.aes.encryption.asymmetrical;

import com.xiaoma.aes.util.BaseUtil;

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;



/**
 * RSA非对称加密算法秘钥生成器
 */
public class KeyGenerator{
    
    /**
     * 初始化公钥和私钥
     * @return
     * @throws NoSuchProviderException
     * @throws NoSuchAlgorithmException
     */
    public static Map<String, Key> initKey(){
        /** RSA算法要求有一个可信任的随机数源 */
        SecureRandom random = new SecureRandom();
        
        KeyPairGenerator keyPairGenerator = null;
        try{
            keyPairGenerator = KeyPairGenerator.getInstance(Encrytion.KEY_ALGORTHM);
        }catch(NoSuchAlgorithmException e){
//            LOGGER.error("系统异常:密钥生成算法(" + Encrytion.KEY_ALGORTHM + ")不存在", e);
//            throw new EncryptionException("系统异常:密钥生成算法({0})不存在", Encrytion.KEY_ALGORTHM);
        }
        
        keyPairGenerator.initialize(Encrytion.KEY_SIZE, random);
        
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        
        /* 生成公钥 */
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        /* 生成私钥 */
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        
        Map<String, Key> keyMap = new HashMap<String, Key>(2);
        keyMap.put(Encrytion.PUBLIC_KEY, publicKey);
        keyMap.put(Encrytion.PRIVATE_KEY, privateKey);
        return keyMap;
    }
    
    /**
     * 获取公钥，并转化为十六进制字符串
     * @param keyMap
     * @return
     */
    public static String getPublicKey(Map<String, Key> keyMap){
        Key key = keyMap.get(Encrytion.PUBLIC_KEY);
        return BaseUtil.parseByte2HexStr(key.getEncoded());
    }
    
    /**
     * 获取私钥，并转化为十六进制字符串
     * @param keyMap
     * @return
     */
    public static String getPrivateKey(Map<String, Key> keyMap){
        Key key = keyMap.get(Encrytion.PRIVATE_KEY);
        
        return BaseUtil.parseByte2HexStr(key.getEncoded());
    }
}
